package cn.iocoder.yudao.module.xhyy.service.knowledge;

import cn.hutool.core.util.IdUtil;
import cn.iocoder.yudao.module.xhyy.controller.app.knowledge.vo.AppKnowledgePageReqVO;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;

import cn.iocoder.yudao.module.xhyy.controller.admin.knowledge.vo.*;
import cn.iocoder.yudao.module.xhyy.dal.dataobject.knowledge.KnowledgeDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;

import cn.iocoder.yudao.module.xhyy.dal.mysql.knowledge.KnowledgeMapper;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.sypz.enums.ErrorCodeConstants.KNOWLEDGE_NOT_EXISTS;

/**
 * 知识点 Service 实现类
 *
 * @author duanxinli
 */
@Service
@Validated
public class KnowledgeServiceImpl implements KnowledgeService {

    @Resource
    private KnowledgeMapper knowledgeMapper;

    @Override
    public String createKnowledge(KnowledgeSaveReqVO createReqVO) {
        // 插入
        KnowledgeDO knowledge = BeanUtils.toBean(createReqVO, KnowledgeDO.class);
        knowledge.setId(IdUtil.fastSimpleUUID());
        knowledgeMapper.insert(knowledge);
        // 返回
        return knowledge.getId();
    }

    @Override
    public void updateKnowledge(KnowledgeSaveReqVO updateReqVO) {
        // 校验存在
        validateKnowledgeExists(updateReqVO.getId());
        // 更新
        KnowledgeDO updateObj = BeanUtils.toBean(updateReqVO, KnowledgeDO.class);
        knowledgeMapper.updateById(updateObj);
    }

    @Override
    public void deleteKnowledge(String id) {
        // 校验存在
        validateKnowledgeExists(id);
        // 删除
        knowledgeMapper.deleteById(id);
    }

    private void validateKnowledgeExists(String id) {
        if (knowledgeMapper.selectById(id) == null) {
            throw exception(KNOWLEDGE_NOT_EXISTS);
        }
    }

    @Override
    public KnowledgeDO getKnowledge(String id) {
        return knowledgeMapper.selectById(id);
    }

    @Override
    public PageResult<KnowledgeDO> getKnowledgePage(KnowledgePageReqVO pageReqVO) {
        return knowledgeMapper.selectPage(pageReqVO);
    }

    @Override
    public PageResult<KnowledgeDO> getKnowledgePage(AppKnowledgePageReqVO pageReqVO) {
        return knowledgeMapper.selectPage(pageReqVO);
    }

}